package com.huizhonglm.diap.api;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.core.utils.LogUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-04-14 16:33
 */
public class HttpImpl implements Http {

    private static final Object lock = new Object();
    private static HttpImpl instance;

    private static final String TAG = "DIAP_API";

    public static HttpImpl registerInstance() {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new HttpImpl();
                }
            }
        }
        return instance;
    }

    private HttpImpl() {
    }

    @Override
    public void post(final String apiName, RequestParams params, final HttpCallback callback) {
        logParams(apiName, params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                logSuccess(apiName, result);
                if (callback != null) {
                    callback.onSuccess(result);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                logFailure(apiName);
                if (callback != null) {
                    callback.onFailure(ex);
                }
                if (ex != null) {
                    ex.printStackTrace();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void logParams(String apiName, RequestParams params){
        LogUtil.print(TAG, "http :: [" + apiName + "] ----------------------------------");
        if (params != null) {
            LogUtil.print(TAG, "http :: [" + apiName + "] - request -" + params.getUrl());
            LogUtil.print(TAG, "http :: [" + apiName + "] - request -" + params.toJson());
        }
    }

    private void logSuccess(String apiName, String result){
        if (EmptyUtil.isEmpty(result)) {
            LogUtil.print(TAG, "http :: [" + apiName + "] - response - result is null !");
        } else {
            LogUtil.print(TAG, "http :: [" + apiName + "] - response - " + JSON.toJSON(result));
        }
        LogUtil.print(TAG, "http :: [" + apiName + "] ----------------------------------");
    }

    private void logFailure(String apiName){
        LogUtil.print(TAG, "http :: [" + apiName + "] - response - api requested fail !");
        LogUtil.print(TAG, "http :: [" + apiName + "] ----------------------------------");
    }
}
